package cn.beforedark.yygh.hosp.service.impl;

import cn.beforedark.yygh.common.exception.YyghException;
import cn.beforedark.yygh.common.helper.HttpRequestHelper;
import cn.beforedark.yygh.common.util.StrUtil;
import cn.beforedark.yygh.hosp.mapper.HospitalSetMapper;
import cn.beforedark.yygh.hosp.service.HospitalSetService;
import cn.beforedark.yygh.model.hosp.HospitalSet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Service
public class HospitalSetServiceImpl extends ServiceImpl<HospitalSetMapper, HospitalSet> implements HospitalSetService {


    private String getSignKey(String hoscode) {
        HospitalSet hospitalSet = null;
        try {
            QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
            wrapper.eq("hoscode", hoscode);
            hospitalSet = baseMapper.selectOne(wrapper);
        } catch (NullPointerException e) {
            return null;
        }
        return hospitalSet.getSignKey();
    }

    /**
     * 身份校验
     */
    @Override
    public Map<String, Object> check(HttpServletRequest request) {
        // 对于HTTP servlet，参数包含在查询字符串或发布的表单数据中。
        Map<String, String[]> parameterMap = request.getParameterMap();

        // 只取value中的第一个值  map: 请求参数 Map
        Map<String, Object> map = HttpRequestHelper.switchMap(parameterMap);

        // 校验秘钥
        String hoscode = (String) map.get("hoscode");
        String y = getSignKey(hoscode);
        String x = (String) map.get("sign");
        if (!StrUtil.hasTextCompare(x, y)) {
            throw new YyghException("医院信息不存在");
        }

        return map;
    }
}
